using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using XjjXmm.Infrastructure.Repository;

namespace Blog.Repository.Permission;



/// <summary>
/// 权限
///</summary>
public class PermissionRepository : RepositoryBase<PermissionEntity>, IPermissionRepository
{
    public PermissionRepository(ISqlSugarClient context, IRepositoryQuery<PermissionEntity> repositoryQuery) : base(context, repositoryQuery)
    {
    }

    public async Task<List<PermissionEntity>> GetMenuPermissionByUserId(long userId)
    {
        var res = await _context.Queryable<PermissionEntity>()
            .Where(a => new[] { (int)PermissionType.Group, (int)PermissionType.Menu }.Contains(a.Type))
            .InnerJoin<RolePermissionEntity>((a, rp) => a.Id == rp.PermissionId)
            .InnerJoin<UserRoleEntity>((a, rp, ur) => rp.RoleId == ur.RoleId && ur.UserId == userId)
            .OrderBy(a => a.ParentId)
            .OrderBy(a => a.Sort)
            .Mapper(it => it.View, it => it.ViewId, it => it.View.Id)
            .ToListAsync();

        return res;
    }

    public async Task<IEnumerable<PermissionEntity>> GetDotPermissionByUserId(long userId)
    {
        var res = await _context.Queryable<PermissionEntity>()
            .Where(a => a.Type == (int)PermissionType.Dot)
            .InnerJoin<RolePermissionEntity>((a, rp) => a.Id == rp.PermissionId)
            .InnerJoin<UserRoleEntity>((a, rp, ur) => rp.RoleId == ur.RoleId && ur.UserId == userId)
            .ToListAsync();

        return res;
    }

    public async Task<object> GetPermissionList()
    {
        /* var permissions = await _permissionRepository.Select
             .WhereIf(_appConfig.Tenant && User.TenantType == TenantType.Tenant, a =>
                 _tenantPermissionRepository
                 .Where(b => b.PermissionId == a.Id && b.TenantId == User.TenantId)
                 .Any()
             )
             .OrderBy(a => a.ParentId)
             .OrderBy(a => a.Sort)
             .ToList(a => new { a.Id, a.ParentId, a.Label, a.Type });   */

        var permissions = await _context.Queryable<PermissionEntity>().OrderBy(a => a.ParentId)
             .OrderBy(a => a.Sort).ToListAsync();

        var apis = permissions
            .Where(a => a.Type == (int)PermissionType.Dot)
            .ToList();

        var menus = permissions
            .Where(a => (new[] { (int)PermissionType.Group, (int)PermissionType.Menu }).Contains(a.Type))
            .Select(a => new
            {
                a.Id,
                a.ParentId,
                a.Label,
                Apis = apis.Where(b => b.ParentId == a.Id).Select(b => new { b.Id, b.Label })
            })
            .ToList();

        return menus;

    }
}

